<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.roleCode" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.roleName" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.enableFlag" placeholder="启用标记" clearable style="width: 150px !important;" class="filter-item">
        <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" size="small" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="info" size="small" icon="el-icon-refresh" @click="handleReset">
        重置
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" align="center" width="225" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="handleAuth(row)">
            授权
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="roleCode" sortable="custom" min-width="20%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.roleCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName" sortable="custom" min-width="20%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="默认标志" prop="defaultFlag" :formatter="formatter" sortable="custom" min-width="10%" header-align="center" align="center" />
      <el-table-column label="启用标志" prop="enableFlag" :formatter="formatter" sortable="custom" min-width="10%" header-align="center" align="center" />
      <el-table-column label="角色描述" prop="roleDesc" sortable="custom" min-width="30%" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.roleDesc }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog title="角色授权资源" top="1vh" :visible.sync="dialogTreeVisible" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" center>
      <el-tree
        v-if="dialogTreeVisible"
        ref="resTree"
        :data="resTreeData"
        node-key="value"
        :check-strictly="true"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpanded"
        :default-checked-keys="defaultChecked"
        show-checkbox
        :props="defaultProps"
        @check="handleResNodeClick"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">
          取消
        </el-button>
        <el-button :loading="ajaxLoading" type="primary" @click="handleUpdateRoleResAuth()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" class="form-center">
        <el-form-item label="角色编号" prop="roleCode">
          <el-input v-model="temp.roleCode" maxlength="64" :disabled="dialogStatus==='update'" />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName" maxlength="64" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="temp.roleDesc" autosize type="textarea" :rows="3" maxlength="128" show-word-limit />
        </el-form-item>
        <el-form-item label="启用标志" prop="enableFlag">
          <el-select v-model="temp.enableFlag" clearable class="filter-item">
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认标志" prop="defaultFlag">
          <el-select v-model="temp.defaultFlag" clearable class="filter-item">
            <el-option v-for="item in defaultFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button :loading="ajaxLoading" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createAuthRole, updateAuthRole, deleteAuthRole, updateRoleResAuth, getResourceTree, getRoleResList } from '@/api/base/auth/authRole'
import Pagination from '@/components/Pagination'
import { setOptionData, valueFormate } from '@/utils/dict'
export default {
  name: 'AuthRole',
  components: { Pagination },
  data() {
    return {
      enableFlagOptions: [],
      defaultFlagOptions: [],
      list: null,
      resTreeData: null,
      total: 0,
      selectedRoleId: null,
      uploadExcelDialogVisible: false,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        roleCode: '',
        roleName: '',
        enableFlag: ''
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      temp: {
        id: null,
        roleCode: '',
        roleName: '',
        roleDesc: '',
        defaultFlag: 'N',
        enableFlag: 'Y',
        createAt: undefined,
        createBy: '',
        updateAt: undefined,
        updateBy: ''
      },
      dialogTreeVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新角色信息',
        create: '新建角色信息'
      },
      defaultChecked: [],
      defaultExpanded: [],
      rules: {
        roleCode: [{ required: true, message: '角色编号不能为空', trigger: 'change' }],
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'change' }],
        roleDesc: [{ max: 128, message: '角色描述长度不能大于128个字符', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }],
        defaultFlag: [{ required: true, message: '默认标记不能为空', trigger: 'change' }]
      },
      ajaxLoading: false
    }
  },
  created() {
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('YES_OR_NO', this.defaultFlagOptions)
    optionsMap.set('ENABLE_FLAG', this.enableFlagOptions)
    setOptionData(optionsMap)

    // 加载资源数信息
    getResourceTree().then(response => {
      this.resTreeData = response.data
    })

    this.getList()
  },
  methods: {
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        sortField: undefined,
        sortOrder: undefined,
        roleCode: '',
        roleName: '',
        enableFlag: ''
      }
    },
    handleCreate() {
      this.temp = {
        id: null,
        roleCode: '',
        roleName: '',
        roleDesc: '',
        defaultFlag: 'N',
        enableFlag: 'Y',
        createAt: undefined,
        createBy: '',
        updateAt: undefined,
        updateBy: ''
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ajaxLoading = true
          createAuthRole(this.temp).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.ajaxLoading = false
            this.$message({
              message: '角色信息保存成功！',
              type: 'success'
            })
          }, response => {
            this.ajaxLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAuth(row) {
      getRoleResList(row.id).then(response => {
        this.defaultChecked = response.data
        this.defaultExpanded = response.data
        this.selectedRoleId = row.id
        this.dialogTreeVisible = true
      })
    },
    handleUpdateRoleResAuth() {
      const selectedNodes = this.$refs.resTree.getCheckedNodes(false, true)
      const resIds = []
      if (selectedNodes && selectedNodes.length > 0) {
        for (const n of selectedNodes) {
          resIds.push(n.value)
        }
      }
      this.ajaxLoading = true
      updateRoleResAuth(this.selectedRoleId, resIds).then(response => {
        this.ajaxLoading = false
        this.dialogTreeVisible = false
        this.$message({
          message: '角色授权信息保存成功！',
          type: 'success'
        })
      }, response => {
        this.ajaxLoading = false
        this.dialogTreeVisible = false
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '确认删除角色[' + row.roleCode + ']信息？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteAuthRole(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '角色信息删除成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.ajaxLoading = true
          updateAuthRole(this.temp).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.ajaxLoading = false
            this.$message({
              message: '角色信息更新成功！',
              type: 'success'
            })
          }, response => {
            this.ajaxLoading = false
          })
        }
      })
    },
    handleResNodeClick(currentObj, treeStatus) {
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      const selected = treeStatus.checkedKeys.indexOf(currentObj.value) // -1未选中
      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectParentNode(currentObj)
        // 统一处理子节点为相同的勾选状态
        this.selectSubNodes(currentObj, true)
      } else {
        // 未选中 处理子节点全部未选中
        if (currentObj.children && currentObj.children.length !== 0) {
          this.selectSubNodes(currentObj, false)
        }
      }
    },
    // 统一处理子节点为相同的勾选状态
    selectSubNodes(treeList, isSelected) {
      for (const child of treeList.children) {
        this.$refs.resTree.setChecked(child.value, isSelected)
        if (child.children && child.children.length !== 0) {
          this.selectSubNodes(child, isSelected)
        }
      }
    },
    // 统一处理父节点为选中
    selectParentNode(currentObj) {
      const currentNode = this.$refs.resTree.getNode(currentObj)
      if (currentNode.parent.key !== undefined) {
        this.$refs.resTree.setChecked(currentNode.parent, true)
        this.selectParentNode(currentNode.parent)
      }
    }
  }
}
</script>
